// 模拟好友请求数据
const friendRequests = [];


// 获取DOM元素
const triggerBtn = document.getElementById('receive-add-friendReq-trigger');
const modal = document.getElementById('receive-add-friendReq-modal');
const closeBtn = document.getElementById('receive-add-friendReq-modal-close');
const modalBody = document.getElementById('receive-add-friendReq-modal-body');
const badge = document.getElementById('receive-add-friendReq-badge');


// 关闭弹窗的函数
function closeModalAdd() {
    modal.style.display = 'none';
}

// ESC键关闭功能
function handleEscKey(event) {
    if (event.key === 'Escape' && modal.style.display === 'flex') {
        closeModalAdd();
    }
}

// 更新好友请求数量
function updateBadgeCount() {
    badge.textContent = friendRequests.length;
    if (friendRequests.length === 0) {
        badge.style.display = 'none';
    } else {
        badge.style.display = 'flex';
    }
}


// 渲染好友请求列表
function renderFriendRequests(append = '') {
    modalBody.innerHTML = '';

    if (append !== '' && append != null) {
        friendRequests.push(append);

    }
    if (friendRequests.length === 0) {
        modalBody.innerHTML = `
                <div class="receive-add-friendReq-empty">
                    <i class="fas fa-inbox"></i>
                    <div>暂无好友请求</div>
                </div>
            `;
        return;
    }

    // <div class="user-info-online-avatar"><img src="/head-portrait/default.png" class="user-info-avatar user-info-avatar-sm user-info-avatar-left user-info-online-avatar online"><div class="online-indicator" style="display: none;"></div></div>
    friendRequests.forEach(request => {
        const requestElement = document.createElement('div');
        requestElement.className = 'receive-add-friendReq-item';
        requestElement.innerHTML = `
                <div class="user-info-online-avatar">
                    <img src="${request.headPortrait}" class="user-info-avatar user-info-avatar-sm user-info-avatar-left user-info-online-avatar online" alt="头像">
                </div>
                <div class="receive-add-friendReq-info">
                    <div class="receive-add-friendReq-name">${request.name}</div>
                    <div class="receive-add-friendReq-uid">UID: ${request.id}</div>
                    <div class="receive-add-friendReq-message">${request.message}</div>
                </div>
                <div class="receive-add-friendReq-actions">
                    <button class="receive-add-friendReq-btn receive-add-friendReq-accept" data-id="${request.id}">同意</button>
                    <button class="receive-add-friendReq-btn receive-add-friendReq-decline" data-id="${request.id}">拒绝</button>
                </div>
            `;
        modalBody.appendChild(requestElement);
    });

// 添加按钮事件监听
    document.querySelectorAll('.receive-add-friendReq-accept').forEach(btn => {
        btn.addEventListener('click', function () {
            const id = parseInt(this.getAttribute('data-id'));
            acceptFriendRequest(id);
        });
    });

    document.querySelectorAll('.receive-add-friendReq-decline').forEach(btn => {
        btn.addEventListener('click', function () {
            const id = parseInt(this.getAttribute('data-id'));
            declineFriendRequest(id);
        });
    });
}


// 同意好友请求
function acceptFriendRequest(id) {
    if (confirm('确定同意此好友请求吗？')) {
// 在实际应用中，这里应该发送请求到服务器
        const index = friendRequests.findIndex(req => req.id === id);
        if (index !== -1) {
            friendRequests.splice(index, 1);
            renderFriendRequests();
            updateBadgeCount();

            //发送给后端
            agreeRequest(id);

            //这里在重新获取下users 和friends 显示新加的li

            setTimeout(function (){
                getFriendList();
                friendSessionList(id);
                setShowNotification('已同意好友请求');
            },500);

        }
    }
}


// 拒绝好友请求
function declineFriendRequest(friendId) {
    if (confirm('确定要拒绝此好友请求吗？')) {
        let userId = localStorage.getItem("userId");

        // 在实际应用中，这里应该发送请求到服务器
        $.ajax({
            type: 'post',
            url: 'chat/refuseFriends',
            contentType: "application/json",
            data: JSON.stringify({
                userId: userId,
                friendId: friendId
            }),
            success: function (body) {
                let data = body.data;
                if (data.status == "fail") {
                    setShowNotification(data.msg);
                }
            },
            error: function (err) {
                if (err.status == 406) {
                    location.href = "login.html";
                }
            }
            });
        const index = friendRequests.findIndex(req => req.id === friendId);
        if (index !== -1) {
            friendRequests.splice(index, 1);
            renderFriendRequests();
            updateBadgeCount();
            setShowNotification('已拒绝好友请求');
        }
    }
}


// 点击触发按钮打开弹窗
triggerBtn.addEventListener('click', function () {
    modal.style.display = 'flex';
    renderFriendRequests();
});


// 点击关闭按钮关闭弹窗
closeBtn.addEventListener('click', closeModalAdd);

// 点击弹窗外部关闭弹窗
window.addEventListener('click', function (event) {
    if (event.target === modal) {
        closeModalAdd();
    }
});


// 监听ESC键按下事件
document.addEventListener('keydown', handleEscKey);


// 初始化
updateBadgeCount();
